//
//  LYDPopoverSecondView.m
//  HAODE
//
//  Created by LiYinDi on 16/5/26.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "FilterSecondView.h"
#import "FilterSecondTableViewCell.h"
#import "UIViewExt.h"
#import "FilterSecondLevelModel.h"
#import "FilterFirstLevelModel.h"
#define kUIScreenHeight [UIScreen mainScreen].bounds.size.height
#define kUIScreenWidth [UIScreen mainScreen].bounds.size.width
@interface FilterSecondView() <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,FilterSecondCellDelegate>
{
   NSMutableArray *_listArray;
    NSMutableArray *firstLevelModelArray;
  UIButton *startTimeButton;
  UIButton *endTimeButton;
  NSString *StartOrEnd;
    UITextField*searchTextField;
    FilterSecondLevelModel *selectedSecondModel;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *theContentView;
@property (nonatomic, strong) UIButton *alphaBtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *topLineLabel;

@property (nonatomic, strong) UIView *dateView;
@property (nonatomic, strong) UIButton *dateConfirmBtn;
@property (nonatomic, strong) UIDatePicker *datePicker;
@end
@implementation FilterSecondView

-(instancetype)init:(NSMutableArray *)listArray  secondLevelModel:(FilterSecondLevelModel *)secondLevelModel title:(NSString *)title isLikeSearch:(NSString*)isLikeSearch
{
    self=[super init];
    if (self) {
        _listArray=listArray;
        selectedSecondModel=secondLevelModel;
        [self setup:title:isLikeSearch];
//        [self setAutoLayout];
    }
    return self;
}

- (void)setup:(NSString *)titleStr :(NSString *)isLikeSearch
{
   
    _alphaBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_alphaBtn addTarget:self action:@selector(alphaBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_alphaBtn setBackgroundColor: [UIColor clearColor]];
    [self addSubview:_alphaBtn];
    
    _theContentView=[[UIView alloc] init];
    _theContentView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_theContentView];
    
    _cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_cancelBtn setTitleColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
    [_cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [_theContentView addSubview:_cancelBtn];
    
    _titleLabel=[[UILabel alloc] init];
    _titleLabel.text=titleStr;
    _titleLabel.textColor=[UIColor blackColor];
    _titleLabel.textAlignment=NSTextAlignmentCenter;
    [_titleLabel setFont:[UIFont systemFontOfSize:17]];
    [_theContentView addSubview:_titleLabel];
    
    _topLineLabel=[[UILabel alloc] init];
    [_topLineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [_theContentView addSubview:_topLineLabel];
    
    _tableView = [[UITableView alloc] init];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.bounces = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_theContentView addSubview:_tableView];
    
    _dateView=[[UIView alloc] init];
    [self addSubview:_dateView];
    
    _dateConfirmBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_dateConfirmBtn setBackgroundColor:[UIColor colorWithRed:90.0f/255.0f green:130.0f/255.0f blue:26.0f/255.0f alpha:1.0f]];
    [_dateConfirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_dateConfirmBtn setTintColor:[UIColor whiteColor]];
    [_dateConfirmBtn addTarget:self action:@selector(dateConfirmBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_dateView addSubview:_dateConfirmBtn];
    
    _datePicker = [[UIDatePicker alloc] init];
    [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    _datePicker.backgroundColor=[UIColor whiteColor];
    [_dateView addSubview:_datePicker];
    _dateView.hidden=YES;
    
    
    
    if ([isLikeSearch isEqualToString:@"Y"]) {
        UIView*Hview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        Hview.backgroundColor=zuiqianhuiColor;
        _tableView.tableHeaderView=Hview;

        UIButton *sxBtn1 = [[UIButton alloc] initWithFrame:CGRectMake(7, 12, 25, 25)];
        [sxBtn1 setImage:[UIImage imageNamed:@"sousuo"] forState:UIControlStateNormal];
        [Hview addSubview:sxBtn1];
        
        
        searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(sxBtn1.right,0, ScreenWidth*400/750,50)];
        [searchTextField setBorderStyle:   UITextBorderStyleNone]; //外框类型
        searchTextField.placeholder = @" 请输入会员名称/昵称/手机号"; //默认显示的字
        searchTextField.font = [UIFont systemFontOfSize: 14];
        searchTextField.tag=22;
        //    searchTextField.keyboardType = UIKeyboardTypeDecimalPad;
        searchTextField.returnKeyType = UIReturnKeyDone;
        searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        searchTextField.delegate = self;
        [Hview addSubview:searchTextField];
        
        UIView* myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
        myToolBar.backgroundColor=jianpancolor;
        UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
        [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
        [myToolBar addSubview:tubtnDone];
        UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
        [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
        [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
        btnDone111 .titleLabel .font=[UIFont systemFontOfSize:16];
        [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
        [myToolBar addSubview:btnDone111];
        myToolBar.alpha=alp;
        UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
        [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
        [myToolBar addSubview:dabtn];
        searchTextField.inputAccessoryView = myToolBar;
 
    }else{
}
}
-(void)requestFilterList
{
    _listArray=[[NSMutableArray alloc]init];
     firstLevelModelArray=[NSMutableArray array];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:self.typeStr forKey:@"filterType"];

    NSMutableArray *searchBeans=[NSMutableArray array];
    NSMutableDictionary *itemsDic= [NSMutableDictionary dictionary];
    [itemsDic setObject:@"o.MemberID" forKey:@"typeCode"];
    [itemsDic setObject:_titleLabel.text forKey:@"typeName"];
    [itemsDic setObject:@"String" forKey:@"dataType"];
    [itemsDic setObject:@"Y" forKey:@"isSingle"];
    [itemsDic setObject:@"Y" forKey:@"isLikeSearch"];
    [itemsDic setObject:searchTextField.text forKey:@"sword"];
    [itemsDic setObject:@"1" forKey:@"pageIndex"];
    [itemsDic setObject:@"20" forKey:@"pageSize"];
    [searchBeans addObject:itemsDic];

    
    
    [param setValue:searchBeans forKey:@"searchBeans"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self];
//     NSLog(@"arrr#######====%@",param);
    [HttpRequest requestData:@"Common/AdvancedFilterList" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
//                NSLog(@"arrr#######====%@",arrr);
                for (NSDictionary* dicc in arrr )
                {
                    FilterFirstLevelModel *firstLevelModel=[FilterFirstLevelModel dataModelWithDict:dicc];
                    [firstLevelModelArray addObject:firstLevelModel];
                    

                }
             FilterFirstLevelModel *firstModel=firstLevelModelArray[self.parentIndex.intValue];
                _listArray=[firstModel.secondModelArray copy];
                [_tableView reloadData];
                
            }
            else{
                [Global hideProgressHUDInternal:self];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self];
            
            [Global showTextHudSub:severDataDict.resultStr view:self];
        }
        
    }];
    
}




- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self requestFilterList];
    
    [searchTextField resignFirstResponder];
    return YES;
}

-(void)OnTapDone{
     [self requestFilterList];
    [searchTextField resignFirstResponder];
}

-(void)alphaBtnClick
{
    [self dismiss];
}
-(void)cancelBtnClick
{
    [self dismiss];
}
-(void)dateConfirmBtnClick
{
   
    _dateView.hidden=YES;
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSString *str=[NSString stringWithFormat:@"%@", [df stringFromDate:_datePicker.date]];
    
    if ([StartOrEnd isEqualToString:@"Start"])
    {
//        startTimeTextField.text = [NSString stringWithFormat:@"%@", [df stringFromDate:_datePicker.date]];
        
        [startTimeButton setTitle:str forState:UIControlStateNormal];
        [startTimeButton setTitleColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
        
    }else{
        
//        endTimeTextField.text = [NSString stringWithFormat:@"%@", [df stringFromDate:_datePicker.date]];
        [endTimeButton setTitle:str forState:UIControlStateNormal];
        [endTimeButton setTitleColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
    }

    
}
- (void)dateChanged:(id)sender
{
    
    UIDatePicker* picker = (UIDatePicker*)sender;
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSString *str=[NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];

    
    if ([StartOrEnd isEqualToString:@"Start"])
    {
    [startTimeButton setTitle:str forState:UIControlStateNormal];
//        startTimeTextField.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
    }else{
        
//        endTimeTextField.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
        
        [endTimeButton setTitle:str forState:UIControlStateNormal];
    }
    
    
}
-(void)startTimeButtonClick:(nonnull UIButton *)btn
{
    startTimeButton=btn;
    StartOrEnd=@"Start";
    _dateView.hidden=NO;
}
-(void)endTimeButtonClick:(nonnull UIButton *)btn
{
    endTimeButton=btn;
    StartOrEnd=@"End";
    _dateView.hidden=NO;
}
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    if (textField.tag==100) {
//    
//        startTimeTextField=textField;
//        
//    }
//    else
//    {
//        endTimeTextField=textField;
//    }
//     _dateView.hidden=NO;
//    return YES;
//    
//}

- (void)dismiss
{
    //    [self.coverBtn removeFromSuperview];
    [self removeFromSuperview];
    
}

#pragma mark - tableView代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 53;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * const  CellIdentifier = @"FilterTableViewCellIdentifier";
    FilterSecondTableViewCell *cell=( FilterSecondTableViewCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FilterSecondTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    FilterSecondLevelModel *model=_listArray[indexPath.row];
    cell.delegate=self;
    cell.timeConfirmBtn.tag=indexPath.row;
    cell.model=model;
//    cell.startTimeTextField.delegate=self;
//    cell.endTimeTextField.delegate=self;
    
//    cell.startTimeTextField.inputView = [[UIView alloc]initWithFrame:CGRectZero];
//    cell.endTimeTextField.inputView = [[UIView alloc]initWithFrame:CGRectZero];
//    [cell setUserInteractionEnabled:YES];
    
    if ([selectedSecondModel.isCustom isEqualToString:@"Y"]) {
        [cell.startTimeButton setTitle:selectedSecondModel.minValue forState:UIControlStateNormal];
        [cell.endTimeButton setTitle:selectedSecondModel.maxValue forState:UIControlStateNormal];
//        cell.startTimeButton.text=selectedSecondModel.minValue;
//        cell.endTimeTextField.text=selectedSecondModel.maxValue;
        startTimeButton=cell.startTimeButton;
        endTimeButton=cell.endTimeButton;
        [startTimeButton setTitleColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
        [endTimeButton setTitleColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
//        [cell setUserInteractionEnabled:NO];
    }
    else
    {
        [cell.startTimeButton setTitle:@"开始时间" forState:UIControlStateNormal];
        [cell.endTimeButton setTitle:@"结束时间" forState:UIControlStateNormal];
        
       //
    }
   
   
    
    cell.selectedImageView.hidden=YES;
    if ([model.itemName isEqualToString:selectedSecondModel.itemName]) {
        cell.selectedImageView.hidden=NO;
    }
    
       return cell;
    
}


#pragma mark FilterSecondTableViewCellDelegate
-(void)timeConfirmButtonClick:(NSUInteger)tag
{
    if (startTimeButton.titleLabel.text.length==0||[startTimeButton.titleLabel.text isEqualToString:@"开始时间"]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择开始时间" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
        
    }
  else if (endTimeButton.titleLabel.text.length==0||[endTimeButton.titleLabel.text isEqualToString:@"结束时间"]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择结束时间" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
   else  {
        FilterSecondLevelModel *model=_listArray[tag];
        model.minValue=startTimeButton.titleLabel.text;
        model.maxValue=endTimeButton.titleLabel.text;
        model.itemName=[NSString stringWithFormat:@"%@~%@",startTimeButton.titleLabel.text,endTimeButton.titleLabel.text];
        
        //    NSLog(@"~~~~~%@%@",startTimeTextField.text,endTimeTextField.text);
        if ([self.delegate respondsToSelector:@selector(FilterSecondView:cellIndex:)]) {
            [self.delegate FilterSecondView: model cellIndex:tag];
        }
        [self dismiss];

    }
   
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FilterSecondLevelModel *model=_listArray[indexPath.row];
    
//    model.minValue=@"";
//    model.maxValue=@"";
    if ([self.delegate respondsToSelector:@selector(FilterSecondView:cellIndex:)]) {
        [self.delegate FilterSecondView: model cellIndex:indexPath.row];
    }
    [self dismiss];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [_alphaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.top.equalTo(self.mas_top);
        make.bottom.equalTo(self.mas_bottom);
        make.width.equalTo(@45);
    }];
    
    [_theContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_alphaBtn.mas_right);
        make.top.equalTo(self.mas_top);
        make.bottom.equalTo(self.mas_bottom);
        make.right.equalTo(self.mas_right);
    }];
    
    [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left).with.offset(10);
        make.top.equalTo(_theContentView.mas_top).with.offset(25);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
    }];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_theContentView.mas_centerX);
        make.top.equalTo(_theContentView.mas_top).with.offset(25);
        make.height.equalTo(@30);
         make.width.equalTo(@100);
        
    }];
    
    [_topLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left).with.offset(0);
        make.top.equalTo(_theContentView.mas_top).with.offset(63);
        make.height.equalTo(@0.5);
        make.right.equalTo(_theContentView.mas_right).with.offset(0);
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left);
        make.top.equalTo(_topLineLabel.mas_bottom);
        make.bottom.equalTo(_theContentView.mas_bottom).with.offset(0);
        make.right.equalTo(_theContentView.mas_right);
    }];
    
    [_dateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.top.equalTo(self.mas_bottom).with.offset(-195);
        make.height.equalTo(@195);
        make.right.equalTo(self.mas_right);
    }];
    [_dateConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_dateView.mas_left);
        make.right.equalTo(_dateView.mas_right);
        make.bottom.equalTo(_dateView.mas_bottom);
        make.height.equalTo(@44);
    }];
    [_datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_dateView.mas_left);
        make.right.equalTo(_dateView.mas_right);
        make.bottom.equalTo(_dateConfirmBtn.mas_top);
        make.height.equalTo(@150);
    }];

}

@end
